//
//  NetworkTools.swift
//  ImageBrowse
//
//  Created by zs on 16/6/18.
//  Copyright © 2016年 zs. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    case GET
    case POST
}

class NetworkTools: AFHTTPSessionManager {
   //将工具类设计成单例
    static let shareIntance : NetworkTools = {
       
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
     
    }()
}

// MARK:- 封装网络请求的方法
extension NetworkTools{
    func request(requestType : RequestType,URLString : String, parameters : [String : NSObject], finishCallBack : (result : AnyObject?, error : NSError?) -> ()) {
        
       //1.抽取成功的回调
        let successCallback = { (task : NSURLSessionDataTask, result : AnyObject?) -> Void in
            finishCallBack(result: result , error: nil)
        }
        // 2.抽取失败的回调
        let failureCallback = { (task : NSURLSessionDataTask?, error : NSError) -> Void in
            finishCallBack(result: nil , error: error)
        }
        
        
        //3.发送网络请求
        
        if requestType == .GET {
          GET(URLString, parameters: parameters, progress: nil, success: successCallback, failure: failureCallback)
        }else{
          POST(URLString, parameters: parameters, progress: nil, success: successCallback, failure: failureCallback)
        }
        
        
    
    }
}


// MARK:- 发送网络请求
extension NetworkTools {

    func loadHomeData(offset : Int ,finishedCallback : (result : AnyObject) -> ()){
      //1.获取请求的URLString
      let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
      
      //2.获取请求的参数
       let parameters = [
        
        "offset" : "\(offset)",
        "limit"  : "30",
        "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"
        
        ]
      //3.发送网络请求
        NetworkTools.shareIntance.request(.GET, URLString: urlString, parameters: parameters) { (result, error) in
            if error != nil {
              print(error)
              return
            }
//            print(result)
            
            
//            let arr : NSDictionary = result as! NSDictionary

//            arr.writeToFile("/Users/zszone/Desktop/a.plist", atomically: true)
            
            finishedCallback(result : result!)
        }
    }
    
    
    
    
    
    
    

}